import { ref, reactive } from 'vue'
export const AUTHENTICATION_KEY = "_accessToken_";
export let token = "";
export let domain = "https://www.lin-home.com";

export function domainFix (str) {
	str = str.replaceAll("/permanent/", `${domain}/permanent/`);
	str = str.replaceAll("/static/UEditor/", `${domain}/static/UEditor/`);
	
	return str;
}

export function setToken (t) {
	token = t;
	uni.setStorage({
		key: AUTHENTICATION_KEY,
		data: t,
		success() {
		},
		fail(err) {
			uni.showToast({
				"title": err.errMsg,
				duration: 10000
			});
		}
	})
}

export function getToken (callback) {
	let promise = new Promise((resolve, reject) => {
		uni.getStorage({
			key: AUTHENTICATION_KEY,
			success (res) {
				token = res.data;
				if (token) {
					uni.post("/api/auth/ValidateLoginState").then(msg => {
						console.log(JSON.stringify(msg));
						if (!msg.success) {
							setToken("");
						}
						
						resolve(token);
					});
				} else {
					resolve(token);
				}
			},
			fail (err) {
				token = "";
				resolve(token);
			},
		});
	});
	
	return promise;
}